<template>
  <div class="interviewed-page">
    <!-- 搜索区 -->
    <div class="search-bar">
      <el-input
        prefix-icon="el-icon-search"
        v-model="searchKeyword"
        placeholder="搜索姓名/职位"
        size="small"
        style="width: 240px"
        @keyup.enter.native="search"
      ></el-input>

      <el-date-picker
        v-model="filterDate"
        type="daterange"
        size="small"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 240px; margin-left: 10px"
      ></el-date-picker>

      <el-button
        type="primary"
        size="small"
        @click="search"
        style="margin-left: 10px"
      >
        搜索
      </el-button>
      <el-button size="small" @click="handleReset()" style="margin-left: 10px">
        重置
      </el-button>
    </div>

    <!-- 卡片列表 -->
    <div class="card-container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-loading-spinner></el-loading-spinner>
        <p>加载中...</p>
      </div>

      <!-- 空状态 -->
      <div v-else-if="interviewedList.length === 0" class="empty-container">
        <el-empty description="暂无记录"></el-empty>
      </div>

      <el-row :gutter="20" v-else>
        <el-col :span="12" v-for="item in currentPageData" :key="item.id">
          <div class="card-wrapper">
            <!-- 卡片主体 -->
            <div
              class="interview-card"
              :class="{
                active: activeId === item.id,
                hover: hoverId === item.id,
              }"
              @mouseenter="handleMouseEnter(item.id)"
              @mouseleave="handleMouseLeave()"
            >
              <!-- 候选人信息 -->
              <div class="card-header">
                <img :src="item.avatar || defaultAvatar" class="avatar" />

                <div class="user-info">
                  <div class="name">{{ item.name || "未知" }}</div>
                  <div class="education-tag">
                    <el-tag
                      size="mini"
                      :type="getEducationTagType(item.education)"
                    >
                      {{ formatEducation(item.education) }}
                    </el-tag>
                  </div>
                </div>
                <div class="phone">
                  {{ item.phone || "未填写" }}
                </div>
              </div>

              <!-- 基本信息 -->
              <div class="card-body">
                <div class="position-info">
                  <h4 class="position-name">
                    {{ item.positionName || "未知职位" }}
                  </h4>
                </div>
              </div>
            </div>

            <div
              class="card-detail"
              :class="{ expanded: activeId === item.id }"
            >
              <div class="detail-content">
                <div class="expected-info">
                  <p>
                    <span class="label">期望行业：</span
                    >{{ item.expectedIndustry || "未填写" }}
                  </p>
                  <p>
                    <span class="label">期望岗位：</span
                    >{{ item.expectedPosition || "未填写" }}
                  </p>
                  <p>
                    <span class="label">期望薪资：</span
                    >{{ formatSalary(item.expectedSalary) }}
                  </p>
                </div>

                <div class="time-info">
                  <p>
                    <span class="label">创建时间：</span
                    >{{ formatDate(item.createdAt) || "未填写" }}
                  </p>
                  <p>
                    <span class="label">结束时间：</span
                    >{{ formatDate(item.endAt) || "未填写" }}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="pagination" v-if="interviewedList.length > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[6, 12, 18]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { getInterviewList } from "@/api/recuriter/applicationManagement";

export default {
  data() {
    return {
      // 数据列表
      interviewedList: [],
      total: 0,
      currentPage: 1,
      pageSize: 6,
      loading: false,
      defaultAvatar:
        "https://cube.elemecdn.com/3/7c/3ea6beec6434fd293262dd8b1e36jpeg.jpeg",

      activeId: null,
      hoverId: null,

      // 搜索条件
      searchKeyword: "",
      filterDate: [],

      // 学历映射
      educationMap: {
        UNDERGRADUATE: "本科",
        MASTER: "硕士",
        DOCTOR: "博士",
        HIGH_SCHOOL: "高中",
        VOCATIONAL: "专科",
      },
    };
  },
  computed: {
    // 当前页数据
    currentPageData() {
      const start = (this.currentPage - 1) * this.pageSize;
      return this.interviewedList.slice(start, start + this.pageSize);
    },
  },
  created() {
    this.loadData();
  },
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true;
      try {
        const res = await getInterviewList();
        if (res.data?.code === 201) {
          this.interviewedList = res.data.data || [];
          this.total = this.interviewedList.length;
        } else {
          this.$message.error("获取数据失败");
        }
      } catch (error) {
        console.error("加载失败：", error);
        this.$message.error("网络错误，请重试");
      } finally {
        this.loading = false;
      }
    },

    // 搜索功能
    search() {
      this.currentPage = 1;
      this.activeId = null; // 重置展开状态

      // 先获取完整数据
      this.loadData().then(() => {
        let filteredData = [...this.interviewedList];
        if (this.searchKeyword.trim()) {
          const keyword = this.searchKeyword.toLowerCase();
          filteredData = filteredData.filter(
            (item) =>
              (item.name && item.name.toLowerCase().includes(keyword)) ||
              (item.positionName &&
                item.positionName.toLowerCase().includes(keyword)) ||
              (item.expectedPosition &&
                item.expectedPosition.toLowerCase().includes(keyword))
          );
        }

        // 日期筛选
        if (this.filterDate && this.filterDate.length === 2) {
          const [start, end] = this.filterDate;
          filteredData = filteredData.filter((item) => {
            if (!item.endAt) return false;
            const endTime = new Date(item.endAt);
            return endTime >= new Date(start) && endTime <= new Date(end);
          });
        }

        this.interviewedList = filteredData;
        this.total = filteredData.length;
      });
    },

    // 鼠标进入时展开详情
    handleMouseEnter(id) {
      this.hoverId = id;
      this.activeId = id;
    },

    // 鼠标离开时收起详情
    handleMouseLeave() {
      this.hoverId = null;
      this.activeId = null;
    },

    // 格式化学历
    formatEducation(education) {
      return this.educationMap[education] || "未知";
    },

    // 学历标签样式
    getEducationTagType(education) {
      const typeMap = {
        DOCTOR: "warning",
        MASTER: "success",
        UNDERGRADUATE: "primary",
        VOCATIONAL: "info",
        HIGH_SCHOOL: "info",
      };
      return typeMap[education] || "default";
    },

    // 格式化薪资
    formatSalary(salary) {
      if (!salary || salary <= 0) return "未填写";
      return `${(salary / 1000).toFixed(1)}k/月`;
    },

    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return "未填写";
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${(date.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
    },

    // 分页处理
    handleCurrentChange(page) {
      this.currentPage = page;
      this.activeId = null; // 切换页码时重置展开状态
      window.scrollTo({ top: 100, behavior: "smooth" });
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.activeId = null;
    },
    handleReset() {
      this.searchKeyword = "";
      this.filterDate = [];

      this.currentPage = 1;
      this.activeId = null;
      this.hoverId = null;
      this.loadData();
    },
  },
};
</script>

<style scoped>
.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
}
.interviewed-page {
  padding: 20px;
  min-height: calc(100vh - 40px);
}

/* 搜索栏样式 */
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

/* 卡片容器 */
.card-container {
  margin-top: 15px;
}

/* 加载和空状态 */
.loading-container,
.empty-container {
  text-align: center;
  padding: 80px 0;
  color: #606266;
}

.loading-container .el-loading-spinner {
  width: 40px;
  height: 40px;
}

/* 卡片样式 */
.card-wrapper {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

/* 卡片主体样式 */
.interview-card {
  background-color: #fff;
  padding: 15px;
  cursor: pointer;
  position: relative;
  display: flex;
  flex-direction: column;
}

.interview-card.active {
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
}

/* 卡片头部 */
.card-header {
  display: flex;
  align-items: center;
}

.user-info {
  margin-left: 20px;
}

.name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 5px;
}

.phone {
  margin-left: auto;
  color: #606266;
  font-size: 13px;
  white-space: nowrap;
}

/* 卡片主体内容 */
.card-body {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #f0f0f0;
}

.position-info {
  flex: 1;
}

.position-name {
  font-size: 14px;
  font-weight: 500;
}

/* 详情区域 - 直接在当前卡片下方展开 */
.card-detail {
  background-color: #fff;
  overflow: hidden;
  max-height: 0;
  transition: max-height 0.3s ease-out;
}

.card-detail.expanded {
  max-height: 300px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.detail-content {
  padding: 15px;
}

/* 详情内容样式 */
.expected-info,
.time-info {
  margin-bottom: 15px;
  font-size: 13px;
}

.label {
  color: #909399;
  display: inline-block;
  width: 80px;
}

/* 分页样式 */
.pagination {
  margin-top: 30px;
  text-align: right;
  padding: 10px;
}

@media (max-width: 768px) {
  .el-col-sm-12 {
    width: 100% !important;
  }

  .search-bar {
    flex-wrap: wrap;
    gap: 10px;
  }

  .search-bar > * {
    margin-left: 0 !important;
    width: 100% !important;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.card-detail.expanded .detail-content {
  animation: fadeIn 0.3s ease;
}
</style>